import cPickle
import os
import datetime

from general_utilities import *
from screen_info import display, GuilessSplashScreen, show_highscores
from highscores import *

class file_info:
  def __init__(self):
    savefilename = ""
    savefile = None
    # and initialize the version string
    no_file = 0
    try:
      test = open("VERSION.txt",'r')
    except:
      no_file = 1
    if not no_file:
      self.version = test.readline()
      if self.version[len(self.version)-1]=="\n":
        self.version = self.version[:len(self.version)-1]
    else:
      self.version = "?" 
  
  def set_savefilename(self,name,shortname):
    # call for new game
    self.savefilename = name
    self.shortname = shortname
    
  def load_gamestate(self,name):
    # assign this to d
    self.savefilename = name
    try:
      self.savefile = open(self.savefilename,'rb')
    except:
      display.crash("Could not load %s"%self.savefilename)
    old_version = cPickle.load(self.savefile)
    if old_version<>self.version:
      display.simple_info_dialog("Outdated savefile","This savefile was created under a different version of OrbQuest.\nNo guarantees that it will work - proceed at your own peril...")
    d = cPickle.load(self.savefile)
    self.shortname = d.shortname
    self.savefile.close()
    # character pic may have changed
    d.get_character().stats.recalc(d)
    # need to redraw screen
    display.last_room = None
    display.need_to_blit = 1
    return d
   
  def save_gamestate(self,d):
    d.l.known_routes = {}
    d.shortname = self.shortname
    try:
      self.savefile = open(self.savefilename,'wb')
    except:
      display.crash("Could not write to %s"%self.savefilename)
    cPickle.dump(self.version,self.savefile,2) 
    cPickle.dump(d,self.savefile,2)
    self.savefile.close()
    
  def n_of_save_files(self,dir):
    n = 0
    if os.path.exists(dir):
      for i in os.listdir(dir):
        if i[len(i)-3:]=="sav":
          n = n + 1
    else:
      display.crash("The save directory is missing!")
    return n

  def is_save_file_free(self,dir,file):
    if os.path.exists(dir):
      try:
        test = open(dir+"/"+file+".sav",'rb')
      except:
        return 1
      test.close()
      return 0
    else:
      display.crash("The save directory is missing!")

  def end_game(self,d,display,all_characters_down=0):
    if all_characters_down:
      # game over, I think?
      display.simple_info_dialog("Game Over","You perished in the dungeon!\nBetter luck next time!\nPlease send feedback to mail@guildgame.com...")
      if d.get_character().level >= 3:
        self.do_chardump(d,display,dead=1)
      no_file = 0
      try:
        test = open(self.savefilename,'rb')
      except:
        no_file = 1
      if not no_file:
        os.remove(self.savefilename)   
      scores_names_surviveds = get_list_add_highscore('save/highscore.lst',files.shortname,d.get_character().score,0,0)
      show_highscores(scores_names_surviveds[0],scores_names_surviveds[1],scores_names_surviveds[2])
      scores_names_surviveds_tosave = get_list_add_highscore('save/highscore.lst',files.shortname,d.get_character().score,0,1)
      dump_highscores('save/highscore.lst',scores_names_surviveds_tosave[0],scores_names_surviveds_tosave[1],scores_names_surviveds_tosave[2])
    else:
      display.simple_info_dialog("Save and quit","Goodbye! Please send feedback to mail@guildgame.com...") 
      GuilessSplashScreen(None,["Saving the game..."],stop_immediately=1) 
      files.save_gamestate(d) 
    raise SystemExit  
  
  def win_game(self,d,display,message):
    display.simple_info_dialog("Victory!",message)
    winner_score_bonus = 2
    self.do_chardump(d,display,winner=1,survivor=1,score_mult=winner_score_bonus)
    no_file = 0
    try:
      test = open(self.savefilename,'rb')
    except:
      no_file = 1
    if not no_file:
      os.remove(self.savefilename)    
    scores_names_surviveds = get_list_add_highscore('save/highscore.lst',files.shortname,d.get_character().score*winner_score_bonus,1,0)
    show_highscores(scores_names_surviveds[0],scores_names_surviveds[1],scores_names_surviveds[2])
    scores_names_surviveds_tosave = get_list_add_highscore('save/highscore.lst',files.shortname,d.get_character().score*winner_score_bonus,1,1)
    dump_highscores('save/highscore.lst',scores_names_surviveds_tosave[0],scores_names_surviveds_tosave[1],scores_names_surviveds_tosave[2])
    raise SystemExit    

  def exit_dungeon(self,d,display,message):
    display.simple_info_dialog("You have escaped!",message)
    survivor_score_bonus = 1.5
    self.do_chardump(d,display,winner=0,survivor=1,score_mult=survivor_score_bonus)
    no_file = 0
    try:
      test = open(self.savefilename,'rb')
    except:
      no_file = 1
    if not no_file:
      os.remove(self.savefilename)    
    scores_names_surviveds = get_list_add_highscore('save/highscore.lst',files.shortname,d.get_character().score*survivor_score_bonus,1,0)
    show_highscores(scores_names_surviveds[0],scores_names_surviveds[1],scores_names_surviveds[2])
    scores_names_surviveds_tosave = get_list_add_highscore('save/highscore.lst',files.shortname,d.get_character().score*survivor_score_bonus,1,1)
    dump_highscores('save/highscore.lst',scores_names_surviveds_tosave[0],scores_names_surviveds_tosave[1],scores_names_surviveds_tosave[2])
    raise SystemExit    

  def do_chardump(self,d,display,winner=0,survivor=0,dead=0,score_mult=1):
    name = "chardumps/chardump_" + self.shortname + "_" + datetime.datetime.now().strftime("%Y%m%d%H%M%S") + ".txt"
    display.simple_info_dialog("Character dump being created","Saving character dump to: "+name)
    character = d.get_character()
    message = []
    message.append("**********************************************\n")
    message.append("Character dump for OrbQuest version: " + self.version + '\n')
    message.append("**********************************************\n")
    message.append(self.shortname + " the " + role_texts[character.stats.role])
    if dead:
      message.append("He has perished in the dungeon...\n")
    elif winner:
      message.append("He found the Orb of Life and will live for a thousand years!\n")
    elif survivor:
      message.append("He wisely left the dungeon and returned home to his family.\n")
    else:
      message.append("He is exploring the dungeon.\n")
    message.append("Level: " + str(character.level))
    message.append("Score: " + str(int(floor(character.score * score_mult))) + '\n')
    message = message + d.get_final_message()
    message.append("**********************************************\n")
    file = open(name,'w')
    for line in message:
      file.write(line+'\n')
    file.close()
      
files = file_info()




